package jsystem.gdrive;

import com.google.api.client.auth.oauth2.CredentialStore;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.FileList;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Key;
import java.security.KeyStore;
import java.security.Provider.Service;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import jbrowser.JBrowser;
import jbrowser.gui.AbstractPage;

public class GDrive extends AbstractPage {

    private static final char[] PASSWORD = "Password01_".toCharArray();
    private static String CLIENT_ID = "360029598627.apps.googleusercontent.com";
    private static String CLIENT_SECRET = "NlYX4YpnT_PxKHk8YPYSCbXH";
    private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

    public GDrive() throws Exception {
        initComponents();

        java.io.File certFile = new java.io.File(JBrowser.getHome(), "security/gdrive");
        System.out.println("Loading KeyStore " + certFile + "...");
        InputStream in = new FileInputStream(certFile);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(in, "Password01_".toCharArray());
        in.close();
        /* Load the keyStore that includes self-signed cert as a "trusted" entry. */
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        SSLSocketFactory sslSocketFactory = ctx.getSocketFactory();

        HttpTransport httpTransport = new NetHttpTransport.Builder().setSslSocketFactory(sslSocketFactory).build();
//        HttpTransport httpTransport = new NetHttpTransport();

        JsonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential();

        CredentialStore credentialStore = new FileCredentialStore(new java.io.File("D://FileCredentialStore.txt"), jsonFactory);
        if (credentialStore.load("buczkotamas@gmail.com", credential)) {
            System.out.println("Credential.getExpiresInSeconds = " + credential.getExpiresInSeconds());
            if (credential.getExpiresInSeconds() < 1) {
                credential.refreshToken();
                credentialStore.store("buczkotamas@gmail.com", credential);
            }
        } else {
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                    httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
                    .setAccessType("online").setApprovalPrompt("auto").build();
            String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
            System.out.println("Please open the following URL in your browser then type the authorization code:");
            System.out.println("  " + url);
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String code = br.readLine();
            GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
            credential = new GoogleCredential().setFromTokenResponse(response);
            credentialStore.store("buczkotamas@gmail.com", credential);
        }
/*
        //Create a new authorized API client
        Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential).build();

           DefaultMutableTreeNode fileNode = new DefaultMutableTreeNode(certFile.getName());
            rootNode.add(fileNode);

            
        Drive.Files.List request = drive.files().list();
        FileList files = request.execute();
        for (com.google.api.services.drive.model.File file : files.getItems()) {
            System.out.println("OriginalFilename = " + file.getOriginalFilename());
            System.out.println("Title = " + file.getTitle());
            System.out.println("IconLink = " + file.getIconLink());
            System.out.println("MimeType = " + file.getMimeType());
        }

        for (File certFile : file.listFiles()) {
            InputStream in = new FileInputStream(certFile);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(in, PASSWORD);
            in.close();

            DefaultMutableTreeNode fileNode = new DefaultMutableTreeNode(certFile.getName());
            rootNode.add(fileNode);

            fileNode.add(new DefaultMutableTreeNode("Type: " + keyStore.getType()));
            DefaultMutableTreeNode providerNode = new DefaultMutableTreeNode("Provider");
            fileNode.add(providerNode);
            providerNode.add(new DefaultMutableTreeNode("Name: " + keyStore.getProvider().getName()));
            providerNode.add(new DefaultMutableTreeNode("Info: " + keyStore.getProvider().getInfo()));
            providerNode.add(new DefaultMutableTreeNode("Version: " + keyStore.getProvider().getVersion()));
            DefaultMutableTreeNode propertiesNode = new DefaultMutableTreeNode("Properties");
            providerNode.add(propertiesNode);
            for (Object key : keyStore.getProvider().keySet()) {
                propertiesNode.add(new DefaultMutableTreeNode(key.toString() + ": " + keyStore.getProvider().get(key)));
            }
            DefaultMutableTreeNode servicesNode = new DefaultMutableTreeNode("Services");
            fileNode.add(servicesNode);

            for (Service service : keyStore.getProvider().getServices()) {
                DefaultMutableTreeNode serviceNode = new DefaultMutableTreeNode(service.getClassName());
                servicesNode.add(serviceNode);
                serviceNode.add(new DefaultMutableTreeNode("Algorithm: " + service.getAlgorithm()));
                serviceNode.add(new DefaultMutableTreeNode("Type: " + service.getType()));
            }

            DefaultMutableTreeNode certificatesNode = new DefaultMutableTreeNode("Certificates");
            fileNode.add(certificatesNode);

            DefaultMutableTreeNode keysNode = new DefaultMutableTreeNode("Keys");
            fileNode.add(keysNode);

            Enumeration<String> aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (keyStore.isCertificateEntry(alias)) {
                    DefaultMutableTreeNode certificateNode = new DefaultMutableTreeNode(alias);
                    certificatesNode.add(certificateNode);
                    Certificate certificate = keyStore.getCertificate(alias);
                    certificateNode.add(new DefaultMutableTreeNode("Type: " + certificate.getType()));
                    certificateNode.add(new DefaultMutableTreeNode("Encoded: " + certificate.getEncoded()));
                    DefaultMutableTreeNode publicKeyNode = new DefaultMutableTreeNode("PublicKey");
                    certificateNode.add(publicKeyNode);
                    publicKeyNode.add(new DefaultMutableTreeNode("Algorithm: " + certificate.getPublicKey().getAlgorithm()));
                    publicKeyNode.add(new DefaultMutableTreeNode("Format: " + certificate.getPublicKey().getFormat()));
                    publicKeyNode.add(new DefaultMutableTreeNode("Encoded:" + certificate.getPublicKey().getEncoded() == null ? "Not supported." : certificate.getPublicKey().getEncoded().toString()));
                }
                if (keyStore.isKeyEntry(alias)) {
                    DefaultMutableTreeNode keyNode = new DefaultMutableTreeNode(alias);
                    Key key = keyStore.getKey(alias, PASSWORD);
                    keyNode.add(new DefaultMutableTreeNode("Algorithm: " + key.getAlgorithm()));
                    keyNode.add(new DefaultMutableTreeNode("Format: " + key.getFormat()));
                    keyNode.add(new DefaultMutableTreeNode("Encoded:" + key.getEncoded() == null ? "Not supported." : key.getEncoded().toString()));
                }
            }
        }
        treeCert.expandPath(new TreePath(rootNode.getPath()));
        */
    }

    @Override
    public String getTitle() {
        return "CertificateManager";
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        lblMessage = new javax.swing.JLabel();
        splitPane = new javax.swing.JSplitPane();
        scrContent = new javax.swing.JScrollPane();
        txtCert = new javax.swing.JTextArea();
        scrTree = new javax.swing.JScrollPane();
        treeCert = new javax.swing.JTree();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setLayout(new java.awt.GridBagLayout());

        lblMessage.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblMessage.setText("Certificate");
        lblMessage.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        add(lblMessage, gridBagConstraints);

        splitPane.setDividerLocation(200);

        txtCert.setColumns(20);
        txtCert.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        txtCert.setRows(5);
        scrContent.setViewportView(txtCert);

        splitPane.setRightComponent(scrContent);

        scrTree.setViewportView(treeCert);

        splitPane.setLeftComponent(scrTree);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.weighty = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        add(splitPane, gridBagConstraints);

        jTextField1.setText("jTextField1");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        add(jTextField1, gridBagConstraints);

        jButton1.setText("jButton1");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        add(jButton1, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel lblMessage;
    private javax.swing.JScrollPane scrContent;
    private javax.swing.JScrollPane scrTree;
    private javax.swing.JSplitPane splitPane;
    private javax.swing.JTree treeCert;
    private javax.swing.JTextArea txtCert;
    // End of variables declaration//GEN-END:variables
}
